import { defineStore } from 'pinia'
import { ref } from 'vue'
import * as workflowApi from '@/api/workflow'

export const useWorkflowStore = defineStore('workflow', () => {
  // 状态
  const workflows = ref([])
  const currentWorkflow = ref(null)
  const workflowInstances = ref([])
  const currentInstance = ref(null)
  const loading = ref(false)
  const total = ref(0)

  // 获取工作流列表
  const fetchWorkflows = async (params) => {
    loading.value = true
    try {
      const data = await workflowApi.getWorkflowList(params)
      workflows.value = data.items || []
      total.value = data.total || 0
      return data
    } finally {
      loading.value = false
    }
  }

  // 获取工作流详情
  const fetchWorkflowDetail = async (id) => {
    loading.value = true
    try {
      const data = await workflowApi.getWorkflowDetail(id)
      currentWorkflow.value = data
      return data
    } finally {
      loading.value = false
    }
  }

  // 创建工作流
  const createWorkflow = async (data) => {
    return await workflowApi.createWorkflow(data)
  }

  // 更新工作流
  const updateWorkflow = async (id, data) => {
    return await workflowApi.updateWorkflow(id, data)
  }

  // 删除工作流
  const deleteWorkflow = async (id) => {
    return await workflowApi.deleteWorkflow(id)
  }

  // 运行工作流
  const runWorkflow = async (id, data) => {
    return await workflowApi.runWorkflow(id, data)
  }

  // 获取工作流实例列表
  const fetchWorkflowInstances = async (params) => {
    loading.value = true
    try {
      const data = await workflowApi.getWorkflowInstances(params)
      workflowInstances.value = data.items || []
      total.value = data.total || 0
      return data
    } finally {
      loading.value = false
    }
  }

  // 获取工作流实例详情
  const fetchInstanceDetail = async (id) => {
    loading.value = true
    try {
      const data = await workflowApi.getWorkflowInstanceDetail(id)
      currentInstance.value = data
      return data
    } finally {
      loading.value = false
    }
  }

  // 暂停工作流实例
  const pauseInstance = async (id) => {
    return await workflowApi.pauseWorkflowInstance(id)
  }

  // 恢复工作流实例
  const resumeInstance = async (id) => {
    return await workflowApi.resumeWorkflowInstance(id)
  }

  // 重试工作流实例
  const retryInstance = async (id, data) => {
    return await workflowApi.retryWorkflowInstance(id, data)
  }

  // 获取工作流实例日志
  const fetchInstanceLogs = async (id, params) => {
    return await workflowApi.getWorkflowInstanceLogs(id, params)
  }

  return {
    workflows,
    currentWorkflow,
    workflowInstances,
    currentInstance,
    loading,
    total,
    fetchWorkflows,
    fetchWorkflowDetail,
    createWorkflow,
    updateWorkflow,
    deleteWorkflow,
    runWorkflow,
    fetchWorkflowInstances,
    fetchInstanceDetail,
    pauseInstance,
    resumeInstance,
    retryInstance,
    fetchInstanceLogs
  }
})
